﻿using Clinic.Extensions;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.DependencyInjection;
using HandyControl.Collections;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Clinic.ViewModels.Main
{
    public partial class MainContentViewModel : ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<TabItemModel> itemList;

        private TabItemModel? selectedItem;
        public TabItemModel? SelectedItem { get { return selectedItem; } set { selectedItem = value; OnPropertyChanged(); selectedChanged(); } }

        public MainContentViewModel()
        {
            itemList = new ObservableCollection<TabItemModel>();
            Events.OnContentChanged += contentChanged;
        }
        private void contentChanged(string name, object view)
        {
            if (SelectedItem != null && SelectedItem.Title.Equals(name))
            {
                return;
            }
            var item = ItemList.FirstOrDefault(p => p.Title.Equals(name));
            if (item == null)
            {
                ItemList.Add(new TabItemModel(name, view));
                SelectedItem = ItemList.Last();
            }
            else
            {
                if (SelectedItem == null || !SelectedItem.Title.Equals(name))
                    SelectedItem = item;
            }
        }

        private void selectedChanged()
        {
            if (SelectedItem == null)
                Events.OnTabItemChanged?.Invoke(null);
            else
                Events.OnTabItemChanged?.Invoke(SelectedItem.Title);
        }
    }
    public class TabItemModel
    {
        public TabItemModel()
        {

        }
        public TabItemModel(string title, object content)
        {
            Title = title;
            Content = content;
        }
        public string Title { get; set; }
        public object Content { get; set; }
    }
}
